package com.main.service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.generico.base.BaseDaoImpl;
import com.generico.exception.AsiWebException;
import com.main.java.DocumentoAdjunto;
import com.web.util.GenericoUtil;

@Service
public class DocumentoAdjuntoServiceImpl extends BaseDaoImpl implements DocumentoAdjuntoService{

	private static final String SUCCESS = "success";
	private static final String FAILURE = "failure";
	private static final String MESSAGE = "message";

	/* (non-Javadoc)
	 * @see com.main.service.DocumentoAdjuntoService#upload(com.main.java.DocumentoAdjunto, java.lang.Long, org.springframework.web.multipart.commons.CommonsMultipartFile)
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = {Exception.class, AsiWebException.class})
	public Map<String, Object> upload(DocumentoAdjunto documentoAdjunto, Long UploadMaxSize, CommonsMultipartFile uploadFile) throws AsiWebException{

		Map<String, Object> result = new HashMap<String, Object>();
		if(UploadMaxSize > 0 && uploadFile.getSize() > UploadMaxSize){
			result.put(MESSAGE, "Tama\u00F1o de Archivo excede el m\u00E1ximo permitido");
			result.put(FAILURE, true);
			return result;
		}
		int dot = StringUtils.lastIndexOf(uploadFile.getOriginalFilename(), ".");
		String extension = (dot != -1) ? StringUtils.substring(uploadFile.getOriginalFilename(), dot + 1) : "";

		documentoAdjunto.setDocumentoAdjuntoExtension(StringUtils.lowerCase(extension));
		documentoAdjunto.setDocumentoAdjuntoBytes(uploadFile.getBytes());
		if(documentoAdjunto.getDocumentoAdjuntoId() != null && documentoAdjunto.getDocumentoAdjuntoId() > 0) update(documentoAdjunto);
		else save(documentoAdjunto);

		result.put(SUCCESS, true);
		result.put(MESSAGE, "Archivo Cargado con \u00C9xito");
		return result;
	}

	/* (non-Javadoc)
	 * @see com.main.service.DocumentoAdjuntoService#uploadBlob(org.springframework.web.multipart.commons.CommonsMultipartFile, java.lang.Long)
	 */
	@Override
	public void uploadBlob(CommonsMultipartFile uploadFile, Long documentoAdjuntoId, String tipoDigitalizacion) throws AsiWebException{
		Connection con = null;
		try {
			Properties properties = GenericoUtil.getPropertiesFile(GenericoUtil.GEN_WEB_PROPERTIES);
			String jdbcUrl = properties.getProperty("jdbc.url");
			String jdbcUsername = properties.getProperty("jdbc.username");
			String jdbcPassword = properties.getProperty("jdbc.password");
			String jdbcDriver = properties.getProperty("jdbc.driverClassName");
			Class.forName(jdbcDriver).newInstance();
			con = DriverManager.getConnection(jdbcUrl, jdbcUsername, jdbcPassword);
	        con.setAutoCommit(false);
	        

//	        PreparedStatement ps = con.prepareStatement("UPDATE DOCUMENTO_ADJUNTO SET DADJ_BYTES = ? WHERE DADJ_ID = ?");
//	       
//	        oracle.sql.BLOB newBlob = oracle.sql.BLOB.createTemporary(con, false, oracle.sql.BLOB.DURATION_SESSION);
//	        InputStream fileInputStream = uploadFile.getInputStream();
//	        OutputStream outputStream ;
//	        byte[] buffer;
//	        int byteread = 0;
//	        while ((byteread = fileInputStream.read(buffer)) != -1) {
//	            outputStream.write(buffer, 0, byteread);
//	        }
//	        outputStream.close();
//	        fileInputStream.close();
//			fileInputStream.close();
//
//	        ps.setBlob(1, newBlob);
//	        ps.setLong(2, documentoAdjuntoId);
//	        ps.executeUpdate();
//
//	        con.commit();
//	        BLOB.freeTemporary(newBlob);
//			con.close();

			
			
			
//			File file = new File("myimage.gif");
			InputStream fileInputStream = uploadFile.getInputStream();
			PreparedStatement pst ;
			if (tipoDigitalizacion.equals("adjuntarFacturaCompra")) {
				pst = con.prepareStatement("UPDATE COMPRA SET COMPRA_IMAGEN = ? WHERE COMPRA_ID = ?");
			} else {
				pst = con.prepareStatement("UPDATE DOCUMENTO_ADJUNTO SET DADJ_BYTE = ? WHERE DADJ_ID = ?");
			}
					
			
			pst.setBytes(1, getBytes(fileInputStream));
			pst.setLong(2, documentoAdjuntoId);
			pst.executeUpdate();
			pst.close();
			fileInputStream.close();
			
			
		} catch (Exception e) {
			logger.error(e, e);
			throw new AsiWebException("Problemas al carga el archivo");
		}finally{
			try {
				if(con != null && !con.isClosed())
					con.close();
			} catch (Exception e) {
				throw new AsiWebException("Problemas al carga el archivo");
			}
		}
	}
	
	public static byte[] getBytes(InputStream is) throws IOException {

	    int len;
	    int size = 1024;
	    byte[] buf;

	    if (is instanceof ByteArrayInputStream) {
	      size = is.available();
	      buf = new byte[size];
	      len = is.read(buf, 0, size);
	    } else {
	      ByteArrayOutputStream bos = new ByteArrayOutputStream();
	      buf = new byte[size];
	      while ((len = is.read(buf, 0, size)) != -1)
	        bos.write(buf, 0, len);
	      buf = bos.toByteArray();
	    }
	    return buf;
	  }
	
}
